<?php

namespace App\Models\Traits;

use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;

trait LastActivedAtHelper
{
    protected $hash_prefix = 'larabbs2_last_active_at_';
    protected $field_prefix = 'user_';

    public function recordLastActivedAt()
    {
        $date  = Carbon::now()->toDateString();
        $hash  = $this->getHashFromDateString($date);
        $field = $this->getHashField($this->id);

        $now = Carbon::now()->toDateTimeString();
        Redis::hSet($hash, $field, $now);
    }

    public function syncUserActivedAt()
    {
        //$yestoday = Carbon::yesterday()->toDateString();
        $yestoday = Carbon::now()->toDateString();
        $hash     = $this->getHashFromDateString($yestoday);
        $dates    = Redis::hGetAll($hash);
        foreach ($dates as $user_id => $date) {
            $user_id = str_replace($this->field_prefix, '', $user_id);
            if ($user = $this->find($user_id)) {
                $user->last_actived_at = $date;
                $user->save();
            }
        }
        Redis::del($hash);
    }

    public function getLastActivedAtAttribute($value)
    {
        $date  = Carbon::now()->toDateString();
        $hash  = $this->getHashFromDateString($date);
        $field = $this->getHashField($this->id);

        $dateTime = Redis::hGet($hash, $field) ?: $value;
        if ($dateTime) {
            return new Carbon($dateTime);
        } else {
            return $this->ceated_at;
        }
    }

    public function getHashFromDateString($date)
    {
        return $this->hash_prefix . $date;
    }

    public function getHashField($id)
    {
        return $this->field_prefix . $id;
    }
}
